package com.xdf.utils;

import com.alibaba.fastjson.JSON;
import com.xdf.constant.CommonConstant;
import com.xdf.vo.LoginUserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Calendar;
import java.util.Optional;

/**
 * @author chanchaw
 * @create 2025-08-23 7:05
 */
public class TokenParseUtils {

    public static LoginUserInfo parseUserInfo8Token(String token) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        token = Optional.ofNullable(token).orElse("");
        if(token.length() == 0) return null;

        // 通过 token 解析为 Jws 对象，数据储存在 body 中
        Jws<Claims> claimsJws = parseToken(token, getPublicKey());
        Claims body = claimsJws.getBody();
        // token 已过期
        if(body.getExpiration().before(Calendar.getInstance().getTime())) return null;
        // 反序列化并返回 LoginUserInfo
        return JSON.parseObject(body.get(CommonConstant.JWT_USER_INFO_KEY).toString(), LoginUserInfo.class);
    }
    // 使用公钥解析 token
    private static Jws<Claims> parseToken(String token,PublicKey publicKey){
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }
    // 根据公钥字符串生成公钥对象
    private static PublicKey getPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        return RSAUtils.getPublicKey(CommonConstant.PUBLIC_KEY);
    }
}
